package com.jinglin.utils;

import cn.hutool.core.date.DateUtil;
import com.jinglin.property.JingLinMinIOProperties;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.UUID;
@Component
public class UploadUtil {
    @Autowired
    private JingLinMinIOProperties jingLinMinIOProperties;

    public  String fileUpload(MultipartFile multipartFile) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {

        // 创建一个Minio的客户端对象
        MinioClient minioClient = MinioClient.builder()
                .endpoint(jingLinMinIOProperties.getEndpointUrl())
                .credentials(jingLinMinIOProperties.getAccessKey(), jingLinMinIOProperties.getSecretKey())
                .build();

        // 判断桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(jingLinMinIOProperties.getBucketName()).build());
        if (!found) {       // 如果不存在，那么此时就创建一个新的桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(jingLinMinIOProperties.getBucketName()).build());
        } else {  // 如果存在打印信息
            System.out.println("Bucket 'test' already exists.");
        }

        // 设置存储对象名称
        String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
        String uuid = UUID.randomUUID().toString().replace("-", "");
        //20230801/443e1e772bef482c95be28704bec58a901.jpg
        String fileName = dateDir + "/" + uuid + multipartFile.getOriginalFilename();
        System.out.println(fileName);

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(jingLinMinIOProperties.getBucketName())
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
                .object(fileName)
                .build();
        minioClient.putObject(putObjectArgs);

        return  "/" + jingLinMinIOProperties.getBucketName() + "/" + fileName;
    }
}
